package cn.fintecher.pangolin.service.manage.request;

import cn.fintecher.pangolin.common.utils.ZWDateUtil;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;

import java.util.Date;
import java.util.Objects;

/**
 * @Auther: xiaqun
 * @Description: 登录日志查询参数
 * @Date: 15:23 2019/8/23
 */

@Data
public class FindLoginRequest {
    @ApiModelProperty(value = "登录人姓名")
    private String realName;

    @ApiModelProperty(value = "登录人工号")
    private String username;

    @ApiModelProperty(value = "IP地址")
    private String ip;

    @ApiModelProperty(value = "最小登录时间")
    private String minLoginTime;

    @ApiModelProperty(value = "最大登录时间")
    private String maxLoginTime;

    @ApiModelProperty(value = "登录类型")
    private String type;

    @ApiModelProperty(value = "是否登录成功")
    private String isSuccess;

    public BoolQueryBuilder generateBuilder() {
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        if (StringUtils.isNotBlank(this.realName)) {
            builder.must(QueryBuilders.wildcardQuery("realName.keyword", "*" + StringUtils.trim(this.realName) + "*"));
        }
        if (StringUtils.isNotBlank(this.username)) {
            builder.must(QueryBuilders.wildcardQuery("username.keyword", "*" + StringUtils.trim(this.username) + "*"));
        }
        if (StringUtils.isNotBlank(this.ip)) {
            builder.must(QueryBuilders.wildcardQuery("ip.keyword", "*" + StringUtils.trim(this.ip) + "*"));
        }
        if (Objects.nonNull(this.minLoginTime)) {
            builder.must(QueryBuilders.rangeQuery("loginTime").gte(ZWDateUtil.getUtilDate(this.minLoginTime).getTime()));
        }
        if (Objects.nonNull(this.maxLoginTime)) {
            String date = this.maxLoginTime + " 23:59:59";
            builder.must(QueryBuilders.rangeQuery("loginTime").lte(ZWDateUtil.getUtilDate(date, "yyyy-MM-dd HH:mm:ss").getTime()));
        }
        if (StringUtils.isNotBlank(this.type)) {
            builder.must(QueryBuilders.matchPhraseQuery("type", this.type));
        }
        if (StringUtils.isNotBlank(this.isSuccess)) {
            builder.must(QueryBuilders.matchPhraseQuery("isSuccess", this.isSuccess));
        }
        return builder;
    }
}
